package com.leonzx.base.controller;

import com.leonzx.base.controller.base.BaseController;
import org.apache.shiro.authz.UnauthorizedException;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.multipart.MultipartException;

import javax.servlet.http.HttpServletRequest;
import java.io.PrintWriter;
import java.io.StringWriter;

/**
 * Created by liang on 2017/7/26.
 */
@ControllerAdvice
public class ErrorController extends BaseController {

    @ExceptionHandler(value = Exception.class)
    public String defaultErrorHandler(HttpServletRequest req, Exception e, Model model) throws Exception {

        //没有相应权限
        if (e instanceof UnauthorizedException) {
            return "common/403";
        }

        if (e instanceof MultipartException) {
            model.addAttribute("exception", e.toString());
            model.addAttribute("url", req.getRequestURL() + "?" +  req.getQueryString());
            model.addAttribute("message", "上传附件太大了。");
            return "common/500";
        }

        model.addAttribute("exception", e.toString());
        model.addAttribute("url", req.getRequestURL() + "?" +  req.getQueryString());
        model.addAttribute("message", e.getMessage());

        StringWriter sw = new StringWriter();
        PrintWriter pw = new PrintWriter(sw);
        e.printStackTrace(pw);
        e.printStackTrace();
        model.addAttribute("pst", sw.toString());
        return "common/500";
    }
}
